package org.nemanjaristic.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.nemanjaristic.utils.RDFUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.facebookapi.FacebookException;
import com.google.code.facebookapi.FacebookJaxbRestClient;
import com.google.code.facebookapi.FacebookWebappHelper;
import com.google.code.facebookapi.FacebookXmlRestClient;
import com.google.code.facebookapi.Permission;
import com.google.code.facebookapi.ProfileField;
import com.google.code.facebookapi.schema.FriendsGetResponse;
import com.google.code.facebookapi.schema.User;
import com.google.code.facebookapi.schema.UsersGetInfoResponse;

/**
 * Servlet implementation class Receive
 */
public class Receive extends HttpServlet {

	private static Logger logger = LoggerFactory.getLogger(Receive.class);

	private static final long serialVersionUID = 1L;

	private static RDFUtils utils;

	String apiKey = "f8621c7b058da215191742e02975790b";
	String secretKey = "ec61fed4e45c60378b1e82524f733764";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Receive() {
		super();
	}

	@Override
	public void init() throws ServletException {
		super.init();
		utils = new RDFUtils();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		proccess(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		proccess(request, response);

	}

	@SuppressWarnings("unchecked")
	private void proccess(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		List<User> users = new ArrayList<User>();
		PrintWriter out = response.getWriter();
		FacebookJaxbRestClient client = (FacebookJaxbRestClient) request.getSession().getAttribute("client");
		if (client == null) {
			logger.info("Not user from session");
			client = new FacebookJaxbRestClient(apiKey, secretKey);
		}
		if (client != null) {
			@SuppressWarnings("unused")
			FacebookWebappHelper facebook = new FacebookWebappHelper(request, response, apiKey, secretKey, client);
			try {
				logger.debug("Cache session key: {}", client.getCacheSessionKey());
				FacebookXmlRestClient.initJaxbSupport();
				long userId = client.users_getLoggedInUser();
				logger.debug("User id: {}", userId);
				List<Long> myid = new ArrayList<Long>(1);
				List<ProfileField> fields = new ArrayList<ProfileField>();
				fields.add(ProfileField.UID);
				fields.add(ProfileField.FIRST_NAME);
				fields.add(ProfileField.NAME);
				fields.add(ProfileField.BIRTHDAY);
				fields.add(ProfileField.PROFILE_URL);
				fields.add(ProfileField.STATUS);
				fields.add(ProfileField.PIC);
				myid.add(userId);
				if (!client.users_hasAppPermission(Permission.STATUS_UPDATE)) {
					logger.info("Client doesn't have publish permissions.");
					redirctToPage(request, response, "publish_stream");
					return;
				}

				if (!client.users_hasAppPermission(Permission.OFFLINE_ACCESS, userId)) {
					logger.info("Client doesn't have offline access.");
					redirctToPage(request, response, "offline_access");
					return;
				}
				logger.info("Application has permissons.");
				FriendsGetResponse friends = (FriendsGetResponse) client.friends_get();
				System.err.println("Friends: "+friends);
				List<Long> friendsUids = friends.getUid();
				if(friendsUids != null && !friendsUids.isEmpty()) {
					UsersGetInfoResponse infoResponse = (UsersGetInfoResponse) client.users_getInfo(friendsUids, fields);
					System.out.println("treci");
					users = infoResponse.getUser();
					System.out.println("cetvrti");
					populateModel(users);
					forwardTo(request, response, "WEB-INF/friends.jsp", users);
				}
				else {
					forwardTo(request, response, "WEB-INF/friends.jsp", users, "You don't have any friends");
				}
			}
			catch (FacebookException e) {
				e.printStackTrace();
				logger.warn("Facebook exception !!!!!");
				utils.createRDFModel();
				users = utils.populateUsersFromDB();
				forwardTo(request, response, "WEB-INF/friends.jsp", users);
			}
		}
		else {
			out.print("Client is null.");
		}
	}

	private void redirctToPage(HttpServletRequest request, HttpServletResponse response, String permission) {
		try {
			response.sendRedirect("http://www.facebook.com/authorize.php?api_key=" + apiKey + "&v=1.0&ext_perm=" + permission + "&next=http://127.0.0.1:8080/OPO/rec" + "&cancel_url=http://127.0.0.1:8080/OPO/rec");
		}
		catch (IOException e) {
			e.printStackTrace();
		}

	}

	private void populateModel(List<User> users) {
		utils.createRDFModel();
		utils.populateModel(users);
	}

	private void forwardTo(HttpServletRequest req, HttpServletResponse resp, String pagePath, Object... objects) throws ServletException, IOException {
		RequestDispatcher dispatcher = req.getRequestDispatcher(pagePath);
		req.getSession().setAttribute("users", objects[0]);
		req.getSession().setAttribute("message", objects[1]);
		logger.debug("Forwarding to {}", pagePath);
		dispatcher.forward(req, resp);
	}

}
